package gui

import (
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"gitee.com/xntk2381/cc/vm/module"
)

func init() {
	module.RegDisplayer(NewLocalVariableStoreSwing())
}

type LocalVariableStoreSwing struct{}

func NewLocalVariableStoreSwing() *LocalVariableStoreSwing {
	return &LocalVariableStoreSwing{}
}

func (l *LocalVariableStoreSwing) Display(localVariableStore *module.LocalVariableStore, title string) {
	a := app.New()
	w := a.NewWindow(title)
	w.Resize(fyne.NewSize(500, 400))

	// 创建表格数据
	data := make([]binding.StringList, 0)
	variables := localVariableStore.GetLocalVariables()
	for i, val := range variables {
		row := binding.BindStringList(
			&[]string{fmt.Sprintf("%d", i), fmt.Sprintf("%v", val)},
		)
		data = append(data, row)
	}

	// 创建表格
	table := widget.NewTable(
		func() (int, int) {
			return len(data), 2
		},
		func() fyne.CanvasObject {
			return widget.NewLabel("")
		},
		func(id widget.TableCellID, obj fyne.CanvasObject) {
			label := obj.(*widget.Label)
			if id.Row < len(data) && id.Col < 2 {
				str, _ := data[id.Row].GetValue(id.Col)
				label.SetText(str)
			}
		},
	)

	// 设置表格列名
	table.SetColumnWidth(0, 100) // 索引列宽度
	table.SetColumnWidth(1, 350) // 值列宽度

	// 禁用选择
	table.OnSelected = func(id widget.TableCellID) {
		table.Unselect(id)
	}

	w.SetContent(container.NewScroll(table))
	w.ShowAndRun()
}
